/**
 * @Description: 请求处理方法
 * @Author: zhen
 * @Date: 2023-10-18
 */
import { AxiosError, AxiosResponse } from 'axios';
import { ElMessage } from 'element-plus';
import { globalI18N } from '@/locales';
import { removeToken } from '@/utils/auth';
import { APIResponse } from './types';

// 请求错误处理
export function errorHandle(error: any) {
  if (error?.response) {
    // AxiosError
    const { response } = error as AxiosError<any, any>;
    switch (response?.status) {
      case 401:
        ElMessage.error(globalI18N.t('global.error.401'));
        removeToken();
        break;
      default:
        ElMessage.error(response?.data?.message || error.message);
        break;
    }
  } else if (error?.message) {
    if (error.message === 'Network Error') {
      ElMessage.error(globalI18N.t('global.error.networkError'));
    } else {
      // Error
      ElMessage.error(error.message);
    }
  } else {
    ElMessage.error(error);
  }
  return error;
}

// 请求拒绝处理公共方法
export function rejectHandle(error: AxiosError<unknown, any>, rejectWithValue: (arg: string) => any) {
  if (error?.response?.status === 401) {
    removeToken();
  }
  if ((error as AxiosError).response) {
    return rejectWithValue(((error as AxiosError).response as AxiosResponse<APIResponse<any>>).data.message);
  } else {
    return rejectWithValue(error.message);
  }
}
